package com.hatricks.is.base.async;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static cn.hutool.core.thread.ThreadUtil.sleep;

@Slf4j
public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();
//        test2();
        try {
            Thread t1 = new Thread(() -> {
                System.out.println("你好哇");
                int i = 1 / 0;
            }, "线程1");
            t1.start();
        } catch (Exception e) {
            log.info("捕捉异常");
            e.printStackTrace();
        }
        sleep(2000);
        System.out.println("main");
    }


    public static void test2() throws ExecutionException, InterruptedException {
        CompletableFuture<String> c3 = CompletableFuture.supplyAsync(() -> {
            //可以注释掉做快速返回 start
            sleep(100);
            log.info("👍");
            //可以注释掉做快速返回 end
            return "赞";
        });
//                .thenApply(first -> {
//                    log.info("在看");
//                    return first + ", 在看";
//                })
//                .thenApply(second -> second + ", 转发");
        log.info("三连有没有？");
        log.info(c3.get());
    }

    public static void test1() throws ExecutionException, InterruptedException {
        //无返回值的方法
        CompletableFuture<Void> c1 = CompletableFuture.runAsync(() -> {
            sleep(30);
            System.out.println("运行在一个单独的线程中");
        });
        System.out.println(c1.get());
        //有返回值的方法
        CompletableFuture<String> c2 = CompletableFuture.supplyAsync(() -> {
            sleep(30);
            System.out.println("运行在一个单独的线程中1");
            return "我有返回值1";
        });
        System.out.println(c2.get());
    }
}
